package com.atguigu.guli.service.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.vod.service.VodService;
import com.atguigu.guli.service.vod.utils.ConstantVodUtils;
import com.atguigu.guli.service.vod.utils.InitVodClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/edu/vod")
@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;

    @PostMapping("uploadVideo")
    public R uploadVideo(MultipartFile file) throws IOException {
       String videoId =  vodService.uploadVideo(file);
        return R.ok().data("videoId",videoId);
    }

    @DeleteMapping("deleteVideo/{videoId}")
    public R deleteVideo(@PathVariable String videoId){
        try {
            DefaultAcsClient client = InitVodClient.initAcsClient(ConstantVodUtils.ACCESS_KEY_ID,ConstantVodUtils.ACCESS_KEY_SECRET);
            DeleteVideoRequest request =new DeleteVideoRequest();
            request.setVideoIds(videoId);
            client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id){
        DefaultAcsClient client = InitVodClient.initAcsClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(id);
        try {
            GetVideoPlayAuthResponse acsResponse = client.getAcsResponse(request);
            String playAuth = acsResponse.getPlayAuth();
            return R.ok().data("auth",playAuth);
        } catch (ClientException e) {
          throw new GuliException(20001,"获取凭证失败");
        }

    }
    @DeleteMapping("deletebatch")
    public R deleteBatch(List videoIds){
        try {
            DefaultAcsClient client = InitVodClient.initAcsClient(ConstantVodUtils.ACCESS_KEY_ID,ConstantVodUtils.ACCESS_KEY_SECRET);
            DeleteVideoRequest request =new DeleteVideoRequest();
            String join = StringUtils.join(videoIds, ",");
            request.setVideoIds(join);
            client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }
}
